/**
* @desc:  人员管理-添加人员-对图片进行裁剪
* @author qiankui
* @date 2023-9-13 14:35:32
*/
<template>
    <div>

        <el-dialog append-to-body :close-on-click-modal="false" :before-close="handleCloseDialog" :title="$t('Image editing')" :visible.sync="picClipperFlag" width="40%">
            <el-row type="flex" justify="center">
                <div class="cropper">
                    <vueCropper
                            ref="cropper"
                            :img="option.img"
                            :outputSize="option.size"
                            :outputType="option.outputType"
                            :info="option.info"
                            :full="option.full"
                            :canMove="option.canMove"
                            :canMoveBox="option.canMoveBox"
                            :original="option.original"
                            :autoCrop="option.autoCrop"
                            :autoCropWidth="option.autoCropWidth"
                            :autoCropHeight="option.autoCropHeight"
                            :fixedBox="option.fixedBox"
                            @realTime="realTime"
                    ></vueCropper>
                </div>
                <div class="previewBox">
                    <div :style="previews.div" class="preview mosaicBackground">
                        <img :src="previews.url" :style="previews.img">
                    </div>

                    <br>
                    <el-row>
                        <el-button :title="$t('amplify')" icon="el-icon-zoom-in" circle size="mini"
                                   @click="changeScale(1)"></el-button>
                        <el-button :title="$t('reduce')" icon="el-icon-zoom-out" circle size="mini"
                                   @click="changeScale(-1)"></el-button>
                        <!--下载-->
                        <!--<el-button icon="el-icon-download" circle size="mini"-->
                                   <!--@click="down('blob')"></el-button>-->
                        <!--向左旋转90度-->
                        <el-button :title="$t('rotate')" class="xz" icon="icon iconfont-KUI icon-xuanzhuan" circle size="mini"
                                   @click="rotateLeft"></el-button>
                        <!--向右旋转90度-->
                        <!--<el-button icon="el-icon-refresh-right" circle size="mini"-->
                                   <!--@click="rotateRight"></el-button>-->
                        <!--查看剪切后的效果图（大图）-->
                        <el-button :title="$t('View cropped large image')" icon="el-icon-view" circle size="mini"
                                   @click="previewFn"></el-button>
                    </el-row>
                </div>
            </el-row>
            <!--<span slot="footer" class="dialog-footer">-->
        <!--<el-button @click="handleCloseDialog">取 消</el-button>-->
        <!--<el-button type="primary" @click="saveEditAvatar">确 定</el-button>-->
    <!--</span>-->

            <br>
            <br>
            <div class="footBtnBox">
                <!--取消-->
                <el-button size="small" type="handle" @click="handleCloseDialog">{{this.i18n.t('Cancel')}}</el-button>
                <!--保存-->
                <el-button size="small" type="primary" :saveLoading="saveLoading" @click="save">
                    {{this.i18n.t('save')}}
                </el-button>
            </div>

        </el-dialog>

        <el-dialog @close="dialogVisible=false" append-to-body :visible.sync="dialogVisible" style="text-align: center">
            <el-image fit="contain" style="box-shadow: 8px 8px 20px 0 rgba(55,99,170,.1), -8px -8px 20px 0 #fff;" :src="dialogImageUrl" alt=""></el-image>
        </el-dialog>
    </div>
</template>

<script>
    import { VueCropper } from 'vue-cropper'
    export default {
        name: "picClipper",
        props: {
            picBase64Data:{
                type:String,
                default:""
            },
            picClipperFlag: {
                type: Boolean,
                default: false
            },
            tabsIndex: {
                type: Number,
                default: 0
            },
            picIndex: {
                type: Number,
                default: 0
            },
        },
        components:{
            VueCropper
        },
        data() {
            return {
                imgObj:{
                    width:0,
                    height:0
                },
                previews: {},
                option:    {
                    img: '', // 裁剪图片的地址
                    info: false, // 裁剪框的大小信息
                    outputSize: 1, // 剪切后的图片质量（0.1-1）
                    full: true, // 输出原图比例截图 props名full
                    outputType: 'png', // 裁剪生成额图片的格式
                    canMove: false,  // 能否拖动图片
                    original: false,  // 上传图片是否显示原始宽高
                    canMoveBox: true,  // 能否拖动截图框
                    autoCrop: true, // 是否默认生成截图框
                    // autoCropWidth: 150,
                    // autoCropHeight: 150,
                    fixedBox: false, // 截图框固定大小
                    centerBox: true // 截图框是否被限制在图片里面

                },
                accept:'.jpg,.jp2',
                picSrc: "",
                isJp2: false,
                saveLoading: false,
                fileList: [],
                dialogImageUrl: '',
                dialogVisible: false
            }
        },
        mounted(){
            this.option.img=this.picBase64Data
            console.log('图片数据',this.picBase64Data);
        },
        methods: {
            async save() {
                this.saveLoading = true
                this.$refs.cropper.getCropData(data => {
                    // do something
                    console.log(data)
                    this.$emit('setPicFn', {
                        tabsIndex: this.tabsIndex,
                        picIndex: this.picIndex,
                        showBase64Pic: data
                    })
                    this.saveLoading = false
                    this.handleCloseDialog()
                })


            },
            // 去除base64图片透明部分
            clearblankimg(imgData){
                // 参考https://www.cnblogs.com/Hello233/p/17486711.html
                var _this=this
                var img = new Image(); //创建图片对象
                img.src = imgData;
                img.onload = function() {
                    var c = document.createElement('canvas'); //创建处理画布对象
                    var ctx = c.getContext('2d');
                    c.width = img.width;
                    c.height = img.height;
                    ctx.drawImage(img, 0, 0); //绘制
                    var imgData = ctx.getImageData(0, 0, c.width, c.height).data; //读取图片数据
                    var lOffset = c.width,
                        rOffset = 0,
                        tOffset = c.height,
                        bOffset = 0;
                    for (var i = 0; i < c.width; i++) {
                        for (var j = 0; j < c.height; j++) {
                            var pos = (i + c.width * j) * 4
                            if (imgData[pos] == 255 || imgData[pos + 1] == 255 || imgData[pos + 2] == 255 || imgData[pos + 3] == 255) {
                                bOffset = Math.max(j, bOffset); // 找到有色彩的最下端
                                rOffset = Math.max(i, rOffset); // 找到有色彩的最右端
                                tOffset = Math.min(j, tOffset); // 找到有色彩的最上端
                                lOffset = Math.min(i, lOffset); // 找到有色彩的最左端
                            }
                        }
                    }
                    lOffset++;
                    rOffset++;
                    tOffset++;
                    bOffset++;
                    var x = document.createElement("canvas"); //创建处理后画布对象
                    x.width = rOffset - lOffset;
                    x.height = bOffset - tOffset;
                    var xx = x.getContext("2d");
                    xx.drawImage(img, lOffset, tOffset, x.width, x.height, 0, 0, x.width, x.height); //绘制

                    _this.dialogImageUrl=x.toDataURL()
                    _this.dialogVisible=true

                    // console.log(x.toDataURL()); //得到最终裁剪出来的base64

                }

            },
            previewFn(){
                this.$refs.cropper.getCropData(data => {
                    // do something
                    console.log(data)

                    this.clearblankimg(data)

                })
            },
            // 保存头像修改
            saveEditAvatar() {
                this.editAvatarDialog = false
                this.finish('blob')
            },
// 放大/缩小
            changeScale(num) {
                num = num || 1;
                this.$refs.cropper.changeScale(num);
            },
// 左旋转
            rotateLeft() {
                this.$refs.cropper.rotateLeft();
            },
// 右旋转
            rotateRight() {
                this.$refs.cropper.rotateRight();
            },
// 保存上传图片
            finish(type) {
                if (type === 'blob') {
                    this.$refs.cropper.getCropBlob((data) => {
                        this.avatarURL = window.URL.createObjectURL(data)
                        //访问接口保存到数据库写这儿!
                    })
                } else {
                    this.$refs.cropper.getCropData((data) => {
                        //访问接口保存到数据库写这儿!
                    })
                }
            },
// 实时预览函数
            realTime(data) {
                console.log(data);
                this.previews = data
            },
// 下载图片
            down(type) {
                var aLink = document.createElement('a')
                aLink.download = 'author-img'
                if (type === 'blob') {
                    this.$refs.cropper.getCropBlob((data) => {
                        aLink.href = window.URL.createObjectURL(data)
                        aLink.click()
                    })
                } else {
                    this.$refs.cropper.getCropData((data) => {
                        aLink.href = data;
                        aLink.click()
                    })
                }
            },
// 更换头像--上传本地图片
            uploadImg(file) {
                var _this = this;
                var reader = new FileReader();
                reader.onload = (e) => {
                    let data;
                    if (typeof e.target.result === 'object') {
                        // 把Array Buffer转化为blob 如果是base64不需要
                        data = window.URL.createObjectURL(new Blob([e.target.result]))
                    } else {
                        data = e.target.result
                    }
                    _this.option.img = data
                }
                // 转化为base64
                // reader.readAsDataURL(file.raw)
                // 转化为blob
                reader.readAsArrayBuffer(file.raw);
            },
            handleCloseDialog() {
                this.$emit('update:picClipperFlag', false)
            }
        }
    }
</script>

<style scoped>
    .previewBox {
        text-align: center;
        margin-left: 60px;
    }

    .preview {
        width: 150px;
        height: 150px;
        margin: 0px auto 20px auto;
        border: 1px solid #ccc;
        /*background-image: linear-gradient(45deg,#ccc 25%,transparent 0),linear-gradient(45deg,transparent 75%,#ccc 0),linear-gradient(45deg,#ccc 25%,transparent 0),linear-gradient(45deg,transparent 75%,#ccc 0);*/
        /*background-color:transparent;*/



        overflow: hidden;
    }

    .cropper {
        width: 260px;
        height: 260px;
    }

</style>
<style>
    .xz .iconfont-KUI.icon-xuanzhuan{
        font-size: 12px !important;
    }
</style>